package org.jim.server.command.handler;

import org.jim.common.*;
import org.jim.common.cache.redis.RedisCache;
import org.jim.common.cache.redis.RedisCacheManager;
import org.jim.common.message.MessageHelper;
import org.jim.common.packets.BroadcastBody;
import org.jim.common.packets.BroadcastBody;
import org.jim.common.packets.Command;
import org.jim.common.packets.RespBody;
import org.jim.common.utils.ChatKit;
import org.jim.common.utils.ImKit;
import org.jim.common.utils.JsonKit;
import org.jim.server.command.AbstractCmdHandler;
import org.jim.server.command.CommandManager;
import org.tio.core.ChannelContext;

import java.util.Collection;
import java.util.Set;

public class BroadcastReqHandler extends AbstractCmdHandler {

    RedisCache groupCache = new RedisCache(ImConst.GROUP, -1, -1);

    @Override
    public ImPacket handler(ImPacket packet, ChannelContext channelContext) throws Exception {
        BroadcastBody broadcastBody = null;
        try {
            broadcastBody = JsonKit.toBean(packet.getBody(), BroadcastBody.class);
        } catch (Exception e) {
            //广播请求消息格式不正确
            return ImKit.ConvertRespPacket(new RespBody(Command.COMMAND_BROADCAST_RESP, ImStatus.C10022), channelContext);
        }

//        RespBody resPacket = new RespBody(Command.COMMAND_BROADCAST_RESP, ImStatus.C10050);
//        resPacket.setData(broadcastBody);
//        ImPacket chatPacket = ImKit.ConvertRespPacket(resPacket, channelContext);
        ImPacket chatPacket = new ImPacket(Command.COMMAND_BROADCAST_REQ, new RespBody(Command.COMMAND_BROADCAST_REQ, broadcastBody).toByte());
        if (broadcastBody.getGroupId() != null) {
            String groupId = broadcastBody.getGroupId();
            ImAio.sendToGroup(groupId, chatPacket);
        } else {
            String groupId = "1";
            ImAio.sendToGroup(groupId, chatPacket);
//            Set<String> groups = groupCache.keys("push:group");
//            for (String key : groups) {
//                String groupId = key.substring(key.lastIndexOf(":") + 1);
//                ImAio.sendToGroup(groupId, chatPacket);
//            }
        }
        return ChatKit.sendSuccessRespPacket(channelContext); // ImKit.ConvertRespPacket(resPacket, channelContext);
    }

    @Override
    public Command command() {
        return Command.COMMAND_BROADCAST_REQ;
    }
}
